package com.time.company.webserver.helper;

import android.content.Context;

import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.listener.ResponseListener;
import com.time.company.webserver.listener.SSLContextUtil;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;

import javax.net.ssl.SSLContext;

/**
 * Created by Bing on 2016/8/23.
 * E-mail is tx16bing@163.com
 */
public class WebServerManager {

    private volatile static WebServerManager mInstance;
    private RequestQueue mQueue;

    private WebServerManager() {
        // 私有化构造函数
        // 保证只有一个Queue对象
        this.mQueue = NoHttp.newRequestQueue();
    }

    public static WebServerManager getInstance(){
        if (mInstance == null){
            synchronized (WebServerManager.class){
                if (mInstance == null){
                    mInstance = new WebServerManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * Https请求，带证书。
     */
    private<T> Request<T> httpsVerify(Request<T> request) {
        SSLContext sslContext = SSLContextUtil.getSSLContext();
        if (sslContext != null)
            request.setSSLSocketFactory(sslContext.getSocketFactory());
        return request;
    }

    /**
     * Https请求，不带证书。
     */
    private<T> Request<T> httpsNoVerify(Request<T> request) {
        SSLContext sslContext = SSLContextUtil.getDefaultSLLContext();
        if (sslContext != null)
            request.setSSLSocketFactory(sslContext.getSocketFactory());
        return request;
    }

    /**
     * 添加一个请求到请求队列
     *
     * @param context 上下文
     * @param request 请求对象
     * @param callBack 接受回调结果
     * @param what what，当多个请求用同一个responseListener接受结果时，用来区分请求
     * @param isShowDialog 是否显示dialog
     * @param isCanCancel 请求是否能被用户取消
     * @param isShowError 是否提示用户错误信息
     */
    public<T> void add(Context context, Request<T> request, ResponseCallback<T> callBack,
                       int what, boolean isShowDialog, boolean isCanCancel, boolean isShowError){
        // 以后可能需要修改为Https
        Logger.i("Request parameters " + request.toString());
        request = httpsNoVerify(request);
        this.mQueue.add(what, request, new ResponseListener(request,context,callBack, isShowDialog,
                isCanCancel, isShowError));
    }

}
